package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.cz.nongyetongv5.DBManager.DBManager;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.AdvBean;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.bean.VersionBean;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.DownloadDataUtil;
import com.cz.nongyetongv5.utils.DownloadDataUtil.OnLoginEnd;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;
import com.cz.nongyetongv5.utils.ImageUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.StreamCorruptedException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class StartActivity extends Activity {

	/**
	 * 去主页的Handler的标识代码
	 */
	private static final int GO_LOGIN = 1000;
	/**
	 * 去引导页的Handler的标识代码
	 */
	private static final int GO_GUIDE = 1001;

	/**
	 * 去主页
	 */
	private static final int GO_MAIN = 1002;

	/**
	 * 存数数据的SharedPreferences
	 */
	public static SharedPreferences nongYeTongSharedPreferences = null;

	/**
	 * 数据库工具类
	 */
	private DatabaseHelper db = null;

	/**
	 * 下载工具类
	 */
	private DownloadDataUtil downloadDataUtil = null;

	/**
	 * 根据不同的标识代码去不同的页面
	 */
	private Handler gotoHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case GO_LOGIN:
					// 去登录页面
					goLogin();

					break;
				case GO_GUIDE:
					// 去引导页
					goGuide();
					break;

				case GO_MAIN:

					if (msg.obj != null && msg.obj instanceof User) {

						User user = (User) msg.obj;

						ConfigUtil configUtil = new ConfigUtil(getResources());

						boolean canLogin = configUtil.containerRegionCode(user
								.getKnowRegion() + "");

						if (!canLogin) {

							DialogUtil.showMessageDialog("非法账号,禁止登陆!",
									new OnClickListener() {

										@Override
										public void onClick(View v) {

											goLogin();

										}
									}, StartActivity.this);

							return;

						}

						goMain(user);
					}

					break;

			}

		};
	};
	public String getVersion2() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			return info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 初始化
	 */
	private void init() {
		nongYeTongSharedPreferences = StartActivity.this.getSharedPreferences(
				CommonConstants.SHARED_REFERENCES_TAG, Context.MODE_PRIVATE);

		boolean isFirstIn = nongYeTongSharedPreferences.getBoolean("firstIn",
				true);
		String ver=this.getVersion2();
		if(!ver.equals(nongYeTongSharedPreferences.getString("v__",""))){

			Log.v("debug",">>>");
			//复制预先的db3文件到data/data/com.cz.nongyetongv5/databases下
			DBManager dbHelper = new DBManager(this);
			dbHelper.openDatabase();
			dbHelper.closeDatabase();
			SharedPreferences.Editor editor =nongYeTongSharedPreferences.edit();
			editor.putString("v__",ver);
			editor.commit();
		}


		if (isFirstIn) {
			gotoHandler.sendEmptyMessageDelayed(GO_GUIDE,
					CommonConstants.INTOTIME);
		} else {

			// 如果不是第一次启动则检查是否登录
			checkLogin();
		}

	}

	private ImageView welcomeImage = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.welcome);

		welcomeImage = (ImageView) findViewById(R.id.welcomeImage);

		// 查询出数据库对象
		db = new DatabaseHelper(StartActivity.this, CommonConstants.DBNAME,
				null, CommonConstants.DATABASE_VERSION);

		// 取得验证名和验证密码
		String validateUsername = new ConfigUtil(getResources())
				.getRestUsername();

		String validatePassword = new ConfigUtil(getResources())
				.getRestPassword();

		// 初始化下载工具类
		downloadDataUtil = DownloadDataUtil.getNewInstance();
		downloadDataUtil.setValidatePassword(validatePassword);
		downloadDataUtil.setValidateUserName(validateUsername);

		getVersion();

		final Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				welcomeImage.setBackgroundDrawable(new BitmapDrawable(
						(Bitmap) msg.obj));

				super.handleMessage(msg);
			}
		};
	}

	/**
	 * 去登录页
	 */
	private void goLogin() {

		new AsyncTask<String, String, AdvBean>() {

			@Override
			protected AdvBean doInBackground(String... params) {
				initImageUrl();
				return advBean;
			}

			protected void onPostExecute(AdvBean result) {

				if (result != null) {

					Intent intent = new Intent(StartActivity.this,
							com.cz.nongyetongv5.activity.AdvActivity.class);

					intent.putExtra("adv", result);

					intent.putExtra("to", LoginActivity.class);

					StartActivity.this.startActivity(intent);

					overridePendingTransition(android.R.anim.fade_in,
							android.R.anim.fade_out);

					StartActivity.this.finish();

				} else {
					Intent intent = new Intent(StartActivity.this,
							LoginActivity.class);
					StartActivity.this.startActivity(intent);
					StartActivity.this.finish();
				}

				advBean = null;

			};

		}.execute();

	}

	/**
	 * 去主页
	 *
	 * @param user
	 */
	private void goMain(final User user) {

		new AsyncTask<String, String, AdvBean>() {

			@Override
			protected AdvBean doInBackground(String... params) {
				initImageUrl();
				return advBean;
			}

			protected void onPostExecute(AdvBean result) {

				if (result != null) {

					Intent intent = new Intent(StartActivity.this,
							com.cz.nongyetongv5.activity.AdvActivity.class);

					intent.putExtra("adv", result);
					intent.putExtra("to", MainActivity.class);
					intent.putExtra("user", user);
					StartActivity.this.startActivity(intent);

					overridePendingTransition(android.R.anim.fade_in,
							android.R.anim.fade_out);

					StartActivity.this.finish();

				} else {
					Intent intent = new Intent(StartActivity.this,
							MainActivity.class);
					intent.putExtra("user", user);
					StartActivity.this.startActivity(intent);
					StartActivity.this.finish();
				}

				advBean = null;

			};

		}.execute();

	}

	/**
	 * 去引导页
	 */
	private void goGuide() {

		Intent intent = new Intent(StartActivity.this, GuideActivity.class);
		StartActivity.this.startActivity(intent);

		// 销毁第一个启动窗口
		StartActivity.this.finish();
	}

	/**
	 * 检查是否登录过
	 */
	public void checkLogin() {

		/**
		 * 从shared中读取缓存的用户名和密码
		 */
		SharedPreferences dataSharedPreferences = getSharedPreferences(
				CommonConstants.SHARED_REFERENCES_TAG, Context.MODE_PRIVATE);

		final String username = dataSharedPreferences.getString("username",
				null);
		final String password = dataSharedPreferences.getString("password",
				null);

		final String town_path_id = dataSharedPreferences.getString(
				"town_path_id", null);

		final String showname = dataSharedPreferences.getString("showname",
				null);

		final String localPySimple = dataSharedPreferences.getString(
				"localpysimple", null);

		final String region_longitudeStr = dataSharedPreferences.getString(
				"region_longitude", null);

		final String region_latitudeStr = dataSharedPreferences.getString(
				"region_latitude", null);

		final int region_zoom = dataSharedPreferences.getInt("region_zoom", 13);

		final boolean tester = dataSharedPreferences.getBoolean("tester", true);

		final String realname = dataSharedPreferences.getString(
				"realname", null);
		final String region_name = dataSharedPreferences.getString(
				"region_name", null);
		/**
		 * 信息都不为空
		 */
		if (username != null && password != null && town_path_id != null
				&& CharsetUtil.isNotNull(localPySimple)
				&& CharsetUtil.isNotNull(region_longitudeStr)
				&& CharsetUtil.isNotNull(region_latitudeStr)) {

			// 启动用户名和密码
			Thread userLoginThread = new Thread(new Runnable() {
				@Override
				public void run() {

					String user_isfinedURL = getResources().getString(
							R.string.http_request_user_isfined).trim();

					user_isfinedURL = new ConfigUtil(getResources())
							.getPreHttpUrl() + user_isfinedURL;

					downloadDataUtil.login(username, password, user_isfinedURL,
							StartActivity.this, new OnLoginEnd() {
								@Override
								public void onLoginEnd(User user, int stateCode) {

									if (stateCode == LoginActivity.LOGIN_SUCCESS
											&& user != null) {

										Message message = new Message();
										message.obj = user;
										message.what = StartActivity.GO_MAIN;

										// 调用去主页
										StartActivity.this.gotoHandler
												.sendMessageDelayed(
														message,
														CommonConstants.INTOTIME);

									} else if (stateCode == LoginActivity.NO_NETWORK) {
										user = new User(
												username,
												password,
												town_path_id,
												showname,
												localPySimple,
												Double.parseDouble(region_longitudeStr),
												Double.parseDouble(region_latitudeStr),
												region_zoom, tester,realname,region_name);

										Message message = new Message();
										//
										message.obj = user;
										message.what = StartActivity.GO_MAIN;

										// 调用去主页
										StartActivity.this.gotoHandler
												.sendMessageDelayed(
														message,
														CommonConstants.INTOTIME);
									} else {
										// 其他情况去登录页
										StartActivity.this.gotoHandler
												.sendEmptyMessageDelayed(
														StartActivity.GO_LOGIN,
														CommonConstants.INTOTIME);
									}

								}
							});
				}
			});
			// 让用户登录线程启动
			userLoginThread.start();
		} else {
			//
			StartActivity.this.gotoHandler.sendEmptyMessageDelayed(
					StartActivity.GO_LOGIN, CommonConstants.INTOTIME);
		}

	}

	@Override
	public void onBackPressed() {
	}

	/**
	 * 清理资源
	 */
	@Override
	protected void onDestroy() {

		if (db != null) {

			db.close();
		}

		super.onDestroy();

	}

	/**
	 * 获得服务器的版本
	 */
	private void getVersion() {

		new AsyncTask<Integer, Integer, Integer>() {

			@Override
			protected Integer doInBackground(Integer... params) {
				if (CommonConstants.isNetworkConnected(StartActivity.this)) {
					HttpUtils httpUtils = HttpUtils.getInstance();

					httpUtils.setOnRequestExecuted(new OnRequestExecuted() {

						@Override
						public void onRequestExecuted(int responseCode,
													  String responseBody) {

							try {

								JSONObject jsonObject = new JSONObject(
										responseBody);

								VersionBean maxVersion = new VersionBean();

								String version = jsonObject
										.getString("version");

								boolean must = jsonObject.getBoolean("must");

								JSONArray logArrJson = jsonObject
										.getJSONArray("log");

								maxVersion.getLog().clear();

								for (int i = 0; i < logArrJson.length(); i++) {

									String log = logArrJson.getString(i);

									maxVersion.getLog().add(log);

								}

								maxVersion.getImageDatas().clear();

								JSONArray imageArray = null;

								if (jsonObject.has("images")) {

									imageArray = jsonObject
											.getJSONArray("images");

								}

								if (imageArray != null
										&& imageArray.length() > 0) {

									for (int i = 0; i < imageArray.length(); i++) {

										String imageUrl = imageArray
												.getString(i);

										Map<String, Bitmap> imageMap = new HashMap<String, Bitmap>();

										imageMap.put(imageUrl, null);

										maxVersion.getImageDatas()
												.add(imageMap);

									}
								}

								maxVersion.setVersion(version);

								maxVersion.setMust(must);

								InitApplication application = (InitApplication) getApplicationContext();

								application.setMaxVersion(maxVersion);

							} catch (Exception e) {
							}

						}
					});

					String requestUrl = getString(R.string.get_version_url);

					requestUrl = requestUrl.replaceAll("region_code",
							new ConfigUtil(getResources()).getRegionCode());

					httpUtils.sendRequest(requestUrl, null, "GET", "UTF-8",
							null, null, null);

				}
				return null;
			}

			protected void onPostExecute(Integer result) {

				try {
					PackageManager packageManager = getPackageManager();
					// getPackageName()是你当前类的包名，0代表是获取版本信息
					PackageInfo packInfo = packageManager.getPackageInfo(
							getPackageName(), 0);

					VersionBean versionBean = new VersionBean(
							packInfo.versionName, null);

					InitApplication application = (InitApplication) getApplicationContext();

					application.setVersion(versionBean);

				} catch (NameNotFoundException e) {
				}

				// // 初始化
				init();
			};

		}.execute();

	}

	private AdvBean advBean = null;

	public void clearChache() {
		File advFile = new File(ImageUtil.getThisAppDataFile(), "adv.data");

		if (advFile.exists()) {
			advFile.delete();
		}
	}

	// 获取缓存
	public AdvBean getCacheAdv() {

		AdvBean advBean = null;

		File advFile = new File(ImageUtil.getThisAppDataFile(), "adv.data");

		if (advFile.exists()) {

			try {
				ObjectInputStream fis = new ObjectInputStream(
						new FileInputStream(advFile));
				advBean = (AdvBean) fis.readObject();

				fis.close();
			} catch (StreamCorruptedException e) {
				e.printStackTrace();
			} catch (OptionalDataException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		return advBean;
	}

	/*
	 * 写出缓存
	 */
	public void writeCacheAdv(AdvBean advBean) {

		File advFile = new File(ImageUtil.getThisAppDataFile(), "adv.data");

		try {
			ObjectOutputStream fis = new ObjectOutputStream(
					new FileOutputStream(advFile));

			fis.writeObject(advBean);

			fis.close();
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (OptionalDataException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 获得广告URL
	public void initImageUrl() {

		AdvBean advBean = getCacheAdv();

		if (advBean != null) {

			this.advBean = advBean;

			if (!advBean.isShow()) {
				clearChache();
				this.advBean = null;
			}

		} else {

			final HttpUtils httpUtils = new HttpUtils();

			String requestUrl = getString(R.string.get_version_url);

			requestUrl = requestUrl.replaceAll("region_code", new ConfigUtil(
					getResources()).getRegionCode());

			httpUtils.setOnRequestExecuted(new OnRequestExecuted() {

				@Override
				public void onRequestExecuted(int responseCode,
											  String responseBody) {

					try {

						JSONObject jsonObject = new JSONObject(responseBody);

						if (!jsonObject.isNull("advImage")
								&& jsonObject.has("advImage")
								&& CharsetUtil.isNotNull(jsonObject
								.getString("advImage"))) {

							String advImage = jsonObject.getString("advImage");

							String advTime = jsonObject.getString("advTime");

							String nowTime = new SimpleDateFormat("yyyy-MM-dd")
									.format(new Date());

							StartActivity.this.advBean = new AdvBean();

							StartActivity.this.advBean.setShow(nowTime
									.compareToIgnoreCase(advTime) < 0);

							StartActivity.this.advBean.setTime(advTime);

							StartActivity.this.advBean.setUrl(advImage);

							ByteArrayOutputStream baos = new ByteArrayOutputStream();

							getHttpBitmap(advImage).compress(
									CompressFormat.PNG, 80, baos);

							StartActivity.this.advBean.setBitmapByte(baos
									.toByteArray());

							try {
								baos.close();
							} catch (IOException e) {
								e.printStackTrace();
							}

							if (StartActivity.this.advBean.isShow()) {
								writeCacheAdv(StartActivity.this.advBean);
							} else {
								StartActivity.this.advBean = null;
							}

						}

					} catch (JSONException e) {
						e.printStackTrace();
					}

				}
			});

			if (CommonConstants.isNetworkConnected(StartActivity.this)) {
				httpUtils.sendRequest(requestUrl, null, "GET", "UTF-8", null,
						null, null);
			}

		}

	}

	public static Bitmap getHttpBitmap(String url) {
		URL myFileURL;
		Bitmap bitmap = null;
		try {
			myFileURL = new URL(url);
			// 获得连接
			HttpURLConnection conn = (HttpURLConnection) myFileURL
					.openConnection();
			// 设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
			conn.setConnectTimeout(6000);
			// 连接设置获得数据流
			conn.setDoInput(true);
			// 不使用缓存
			conn.setUseCaches(false);
			// 这句可有可无，没有影响
			conn.connect();
			// 得到数据流
			InputStream is = conn.getInputStream();
			// 解析得到图片
			bitmap = BitmapFactory.decodeStream(is);
			// 关闭数据流
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;

	}
}
